var constant = require('../const');
var models = require('../models');
var AV = require('leanengine')

//每15分清理一次0.25 * 60 * 60;

function clearLover(){
	// 关闭状态为0的女性
  var MLLovers = models.MLLovers;
  var loverQuery = new AV.Query(MLLovers);
  // 
  loverQuery.equalTo("status",0);
  loverQuery.equalTo("gender",2);
  loverQuery.find({
    success: function(results){
      for (var i = 0; i < results.length; i++) {
        var lover = results[i];
        var updateTime = lover.updatedAt.getTime()/1000;
        var nowTime = (new Date()).getTime()/1000;
        var expireSeconds = 0.25 * 60 * 60;
        if (nowTime - updateTime > expireSeconds ) {
          lover.destroy();
          
        };
      };
    },
    error: function(error){
    }
  });
}

//一天清理一次随机电话的男性24
function clearLoverMan(){
	// 关闭状态为1的女性
  var MLLovers = models.MLLovers;
  var loverQuery = new AV.Query(MLLovers);
  // 
  loverQuery.equalTo("status",0);
  loverQuery.equalTo("gender",1);
  loverQuery.find({
    success: function(results){
      for (var i = 0; i < results.length; i++) {
        var lover = results[i];
        var updateTime = lover.updatedAt.getTime()/1000;
        var nowTime = (new Date()).getTime()/1000;
        var expireSeconds = 24 * 60 * 60;
        if (nowTime - updateTime > expireSeconds ) {
          lover.destroy();         
        };
      };
    },
    error: function(error){
    }
  });
}

//5分钟遍历一次正式单，看哪些是异常结束的，然后将之设置为结束
function setOrderFinish(){
  var orderQuery = new AV.Query(models.MLOrder);
  orderQuery.limit(1000); 
  orderQuery.lessThan("status",2);//查找完成的和进行的
  orderQuery.find({
    success:function(orders){     
      if(orders.length>0){
        var now = new Date().getTime();
        for(var i= 0;i<orders.length;i++){
          //如果是等待状态，切时间大于30分，则重置
          var temp = orders[i];
          if(temp.get("status")==0&&now-temp.createdAt.getTime()>=1800000){
            temp.set("status",constant.ORDER_STATUS_CANCEL);
            temp.save();
          }
          //如果是运行状态，但是已经超时
          if(temp.get("status")==1&&now-temp.get("startTime")-temp.get("period")*60*1000>=0){
            temp.set("status",constant.ORDER_STATUS_COMMENT);
            temp.save();
          }
        }
      }
    },
    error:function(error){

    }
  })

}

//1小时遍历一次正式单，若为被取消的单，则退款给发单人，若未评价直接设置好评
function reviewOrder(req,res){
  var orderQuery = new AV.Query(models.MLOrder);
  var temp=null;
  orderQuery.limit(1000); 
  orderQuery.include("sponsor");
  orderQuery.include("winner");
  orderQuery.greaterThan("status",1);//查找已经完成的单
  orderQuery.ascending("status");
  orderQuery.equalTo("commentStatus",null);//未评价的
  orderQuery.find({
    success:function(orders){
      if(orders.length>0){
        var now = new Date().getTime();
        for(var i= 0;i<orders.length;i++){
          //如果是等待评价状态，切时间大于60分，则设置为已评价5星
          temp = orders[i];
          if(temp.get("status")==constant.ORDER_STATUS_COMMENT&&now-temp.get("startTime")-temp.get("period")*60*1000>3600000){
            temp.set("status",constant.ORDER_STATUS_FINISH);
            temp.set("commentStatus",6);
            temp.save(null,{
              success:function(order){
                var user = order.get("winner");
                var balance =user.get("balance")+order.get("cost")/10; 
                user.set("balance",parseFloat(balance.toFixed(2)));
                user.save(null,{
                  success:function(user){
                    AV.Cloud.run('sendSysMsg', {"touserId":user.id,"msg": order.get("sponsor").get("nickname")+"长时间没有评价，你获得了默认好评,获得了"+order.get("cost")+"时光。"}, {
                      success: function(result) {
                          res.success("发送成功");
                        },
                        error: function(error) {
                          res.error("发送失败");
                        }
                    });
                    //保存记录
					AV.Cloud.run("incomeRecord",{"userId":user.id,"price":order.get("cost")/10,"type":constant.INCOME_TYPE_BEBUY,"aboutUserId":order.get("sponsor").id});
                  },
                  error:function(err){
                    console.log(temp.id+"修改默认好评成功，但给钱失败");
                  }
                })
              },
              error:function(){
                console.log(temp.id+"修改默认好评失败");
              }
            })
          }else
          //如果是取消状态，但是已经超时
          if(temp.get("status")==constant.ORDER_STATUS_CANCEL){
            temp.set("status",constant.ORDER_STATUS_DRAWBACK);
            temp.save(null,{
              success:function(order){
                var user = order.get("sponsor");
                var balance =user.get("balance")+order.get("cost")/10; 
                user.set("balance",parseFloat(balance.toFixed(2)));
                user.save(null,{
                  success:function(user){
                    AV.Cloud.run('sendSysMsg', {"touserId":user.id,"msg": order.get("winner").get("nickname")+"长时间没有理会，您的时光已经返还到您的账户，请注意查收。"}, {
                      success: function(result) {
                          res.success("发送成功");
                        },
                        error: function(error) {
                          res.error("发送失败");
                        }
                    });
                    //保存记录
                    AV.Cloud.run("incomeRecord",{"userId":user.id,"price":order.get("cost")/10,"type":constant.INCOME_TYPE_OUTTIME,"aboutUserId":order.get("winner").id});
                  },
                  error:function(){
                    console.log(temp.id+"修改成退款成功，但给钱失败");
                  }
                })
              },
              error:function(){
                console.log(temp.id+"修改成为退款状态失败");
              }
            })
          }
        }
      }
    },
    error:function(error){

    }
  })
}

exports.clearLover = clearLover;
exports.clearLoverMan = clearLoverMan;
exports.setOrderFinish = setOrderFinish;
exports.reviewOrder = reviewOrder;


